﻿using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using DependencyInjectionHelperLib.Attributes;
using DependencyInjectionHelperLib.Navigation;
using MeterReader.Messages;
using MeterReader.Models;
using MeterReader.Services;

namespace MeterReader.ViewModels
{
    [DIRegistration(pageKey: "MetersDataMonitor")]
    public partial class MetersDataMonitorViewModel : ObservableRecipient, IRecipient<WorkStatusMessage>
    {
        private INavigationObjectProvider? _navigationObjectProvider;
        private IDataService? _readService;

        public MetersDataMonitorViewModel() { }

        public MetersDataMonitorViewModel(INavigationObjectProvider navigationObjectProvider, IDataService readService)
        {
            _navigationObjectProvider = navigationObjectProvider;
            _readService = readService;
            MeterDataCollections = _readService.GetMeterDataCollections();
            MeterDataCollections.CollectionChanged += MeterDataCollections_CollectionChanged;
            IsActive = true;
        }

        private void MeterDataCollections_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            GoDeviceDetailViewCommand.NotifyCanExecuteChanged();
        }

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(StartReadCommand))]
        [NotifyCanExecuteChangedFor(nameof(StopReadCommand))]
        private bool _isStarted = false;

        public ObservableCollection<MeterDataCollection> MeterDataCollections { get; set; } = new();

        [RelayCommand(CanExecute = nameof(CanDeviceDetailView))]
        private void GoDeviceDetailView(string key)
        {
            var vm = _navigationObjectProvider!.GetNavigationObject<MetersCurveViewModel>(key);
            _ = WeakReferenceMessenger.Default.Send(new NavigateRequestMessage(vm!));
        }

        [RelayCommand]
        private void GoHistoryView(string key)
        {
            var vm = _navigationObjectProvider!.GetNavigationObject<HistoryViewModel>(key);
            _ = WeakReferenceMessenger.Default.Send(new NavigateRequestMessage(vm!));
        }

        private bool CanDeviceDetailView() => MeterDataCollections.Any();

        [RelayCommand(CanExecute = nameof(CanStart))]
        private void StartRead()
        {
            _readService!.StartPeriodicRead();
            IsStarted = true;
        }

        private bool CanStart() => !IsStarted;

        [RelayCommand(CanExecute = nameof(IsStarted))]
        private void StopRead()
        {
            _readService!.StopPeriodicRead();
            IsStarted = false;
        }

        public void Receive(WorkStatusMessage message)
        {
            IsStarted = message.Working;
        }
    }
}
